package com.lframework.starter.web.core.utils;

import com.lframework.starter.common.utils.StringUtil;
import com.lframework.starter.web.core.annotations.sort.Sort;
import com.lframework.starter.web.core.vo.SortPageVo;
import com.lframework.starter.web.inner.vo.sort.SortVo;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Join查询排序Util
 *
 * @author zmj
 */
public class JoinQuerySortUtil {

    private static final ThreadLocal<List<Sort>> QUERY_SORT_POOL = new InheritableThreadLocal<>();

    private static final ThreadLocal<List<SortPageVo>> QUERY_VO_POOL = new InheritableThreadLocal<>();

    /**
     * 获取查询排序VO
     * @return 查询排序VO列表
     */
    public static List<SortVo> getQuerySortVo() {
        List<SortPageVo> sortPageVos = QUERY_VO_POOL.get();
        if (Objects.nonNull(sortPageVos) && !sortPageVos.isEmpty()) {
            Map<String, String> sortMap = convertSortMap();
            return sortPageVos.stream()
                    .filter(t -> sortMap.containsKey(t.getSortField()))
                    .map(t -> new SortVo(sortMap.get(t.getSortField()), t.getSortOrder()))
                    .distinct()
                    .collect(Collectors.toList());
        }
        return null;
    }

    /**
     * 设置查询排序
     * @param sort 排序
     */
    public static void setQuerySort(Sort sort, List<SortPageVo> sortPageVos) {
        List<Sort> sorts = QUERY_SORT_POOL.get();
        if (sorts == null) {
            sorts = new java.util.ArrayList<>();
            QUERY_SORT_POOL.set(sorts);
        }
        sorts.add(sort);
        QUERY_VO_POOL.set(sortPageVos);
    }

    /**
     * 设置查询排序
     * @param sortList 排序列表
     * @param sortPageVos 排序VO列表
     */
    public static void setQuerySort(List<Sort> sortList, List<SortPageVo> sortPageVos) {
        List<Sort> sorts = QUERY_SORT_POOL.get();
        if (sorts == null) {
            sorts = new java.util.ArrayList<>();
            QUERY_SORT_POOL.set(sorts);
        }
        sorts.addAll(sortList);
        QUERY_VO_POOL.set(sortPageVos);
    }

    /**
     * 清空查询排序
     */
    public static void clear() {
        QUERY_SORT_POOL.remove();
        QUERY_VO_POOL.remove();
    }

    public static Map<String, String> convertSortMap() {
        Map<String, String> sortKeyMap = new HashMap<>();
        Optional.ofNullable(QUERY_SORT_POOL.get())
                .orElseGet(ArrayList::new).forEach(sort -> {
            if (sort.autoParse()) {
                sortKeyMap.put(sort.value(), (StringUtil.isEmpty(sort.alias()) ? "" : (sort.alias() + ".")) + StringUtil.toUnderlineCase(sort.value()));
            } else {
                sortKeyMap.put(sort.value(), "t." + StringUtil.toUnderlineCase(StringUtil.isEmpty(sort.alias()) ? sort.value() : sort.alias()));
            }
        });
        return sortKeyMap;
    }
}
